<template>
  <el-button type="primary" :disabled="disabled" :size="size" @click="downLoad">
    {{ name__ }}<i v-if="disabled" class="el-icon-loading" />
  </el-button>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      default: '下载图片'
    },
    size: {
      type: String,
      default: 'mini'
    },
    img: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      name__: '',
      disabled: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.name__ = this.name
    })
  },
  methods: {
    downLoad() { // 点击 ⌚️
      if (!this.img) {
        this.$message.error('不存在需要下载的图片')
      } else {
        this.disabled = true
        this.name__ = '下载中'
        this.downLoad__() // 创建canvas 下载
      }
    },
    downLoad__() {
      const div = document.createElement('div')
      div.style.cssText = 'position:absolute;z-index:3009'
      const canvas = document.createElement('canvas')
      div.appendChild(canvas)
      document.body.appendChild(div)
      var context = canvas.getContext('2d')
      var img = new Image()
      img.setAttribute('crossOrigin', 'anonymous') // 解决canvas 图片跨域
      img.src = this.img
      const self = this
      img.onload = function() {
        if (img.complete) {
          // 根据图像重新设定了canvas的长宽
          div.style = `width:${img.width}px;height:${img.height}px;`
          canvas.setAttribute('width', img.width)
          canvas.setAttribute('height', img.height)
          // 绘制图片
          context.drawImage(img, 0, 0, img.width, img.height)
          context.strokeStyle = 'orange'
          const url = canvas.toDataURL('image/jpg')
          const a = document.createElement('a')
          document.body.appendChild(a)
          const event = new MouseEvent('click')
          a.download = name || ''
          a.href = url
          a.dispatchEvent(event)
          self.name__ = self.name
          self.disabled = false
          img = null
          document.body.removeChild(div)
          document.body.removeChild(a)
        }
      }
    }
  }
}
</script>
